<template>
  <div class="tag-container">
    <!-- 弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :close-on-click-modal="false"
      width="520px"
      :before-close="handleDialogClose"
    >
      <add-or-edit-tag
        v-if="dialogType === 'add_or_edit'"
        :id="tagId"
        :res-list="tagCloneResList"
        @click="handleDialogClose"
      ></add-or-edit-tag>
    </el-dialog>

    <!-- 操作栏 -->
    <div class="tag-operations">
      <div class="operations-left">
        <el-dropdown placement="bottom-start" class="operation-dropdown">
          <el-button type="primary">
            <i class="el-icon-plus"></i> 添加
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleAddOrEditTag('add')">
              添加Tag资源
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button type="primary" @click="handleAddOrEditTag('edit')" :disabled="!selectedTagId">
          <i class="el-icon-edit"></i> 编辑
        </el-button>
        <el-button type="primary" @click="handleTagOperation(selectedTag, 'start')" :disabled="!selectedTagId">
          <i class="el-icon-video-play"></i> 启动
        </el-button>
        <el-button type="primary" @click="handleTagOperation(selectedTag, 'stop')" :disabled="!selectedTagId">
          <i class="el-icon-video-pause"></i> 停止
        </el-button>
        <el-popover
          placement="top"
          width="220"
          v-model="deleteConfirmVisible"
        >
          <p>确认删除Tag资源?</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="deleteConfirmVisible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="confirmDelete">确认</el-button>
          </div>
          <el-button slot="reference" type="primary" :disabled="!selectedTagId">
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </el-popover>
      </div>
    </div>

    <!-- 表格 -->
    <div class="tag-table">
      <el-table
        ref="tagTable"
        v-loading="tableLoading"
        :data="tagTable"
        row-key="id"
        :header-cell-style="{
          'background-color': '#eceef0',
          'border-top': '4px solid #44b1ff',
          'border-bottom': '2px solid #dedede',
          height: '50px',
          color: '#222',
        }"
        highlight-current-row
        @current-change="handleCurrentChange">
        <!-- 单选列 -->
        <el-table-column type="selection" width="60">
          <template slot-scope="scope">
            <el-radio class="radio" v-model="selectedTagId" :label="scope.row.id">
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>

        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="expand-table">
              <el-table
                :data="props.row.tagsrsc"
                border
                row-key="id"
                :header-cell-style="{
                  'background-color': '#eceef0',
                  'border-top': '4px solid #44b1ff',
                  'border-bottom': '2px solid #dedede',
                  height: '50px',
                  color: '#222',
                }"
                highlight-current-row
              >
                <el-table-column prop="id" label="资源名" sortable min-width="150">
                </el-table-column>
                <el-table-column prop="status" label="状态" sortable max-width="200">
                  <template slot-scope="scope">
                    <el-tooltip effect="dark" :content="parseResStatusMsg(scope.row)" placement="right">
                      <span class="status-badge" :class="'badge-' + parseResStatusColor(scope.row)">
                      </span>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="type" label="资源类型" sortable width="150" />
                <el-table-column prop="svc" label="服务" sortable width="150" />
              </el-table>
            </div>
          </template>
        </el-table-column>

        <!-- Tag名称列 -->
        <el-table-column prop="id" label="Tag名" sortable min-width="150"> </el-table-column>

        <!-- 节点列 -->
        <el-table-column
          v-for="(node, index) in nodeList"
          :key="index"
          :min-width="nodeList.length > 0 ? 760 / nodeList.length : 150"
        >
          <template slot="header">
            <div class="table-header-node" @click="handleClickNode(node)">
              <el-tooltip effect="dark" :content="node.status" placement="top">
                <span
                  class="node-avatar"
                  :class="{
                    'node-running': node.running,
                    'node-stopped': !node.running
                  }"
                >
                  <span v-if="node.type === 'guest' || node.type === 'remote'">
                    {{ node.type === 'guest' ? 'G' : 'R' }}
                  </span>
                  <i v-else class="el-icon-monitor"></i>
                </span>
              </el-tooltip>
              <el-tooltip placement="top-start" :content="node.id">
                <div class="node-name">{{ node.id }}</div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 节点操作面板 -->
    <div v-if="nodePanelVisible" class="node-panel">
      <div class="node-panel-header">
        <h3>节点操作: {{ selectedNode.id }}</h3>
        <el-button type="text" @click="closeNodePanel">
          <i class="el-icon-close"></i>
        </el-button>
      </div>
      <div class="node-panel-content">
        <p>节点状态: {{ selectedNode.status }}</p>
        <p>节点类型: {{ selectedNode.type || 'normal' }}</p>
        <p>运行状态: {{ selectedNode.running ? '运行中' : '已停止' }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import AddOrEditTag from './form/addOrEditTag.vue'
import { tagActions } from '@/api/advanced'
import { parseResStatusMsg, parseResStatusColor } from '@/utils/index'

export default {
  name: 'Tag',
  components: {
    AddOrEditTag
  },
  data() {
    return {
      selectedTagId: '', // 选中的Tag ID
      selectedTag: null, // 选中的Tag对象
      dialogVisible: false, // 弹窗显示状态
      dialogTitle: '', // 弹窗标题
      dialogType: '', // 弹窗类型：add_or_edit
      tagId: '', // 获取资源id（资源名称）
      deleteConfirmVisible: false, // 删除确认弹窗显示状态
      nodePanelVisible: false, // 节点操作面板显示状态
      selectedNode: {} // 选中的节点
    }
  },
  computed: Object.assign(
    {},
    mapGetters('advanced', ['tagLoading', 'tagTable', 'tagCloneResList']),
    mapGetters('node', ['nodeList', 'localnode', 'nodeLoading']),
    mapGetters('cluster', ['clusterName']),
    {
      // 合并loading状态
      tableLoading: function() {
        return this.tagLoading || this.nodeLoading
      }
    }
  ),
  mounted() {
    this.loadData()
  },
  watch: {
    // 监听集群名称变化
    clusterName: function(newVal, oldVal) {
      if (newVal && oldVal && newVal !== oldVal) {
        console.log('集群切换，刷新Tag数据:', newVal)
        this.loadData()
      }
    }
  },
  methods: Object.assign(
    {},
    mapActions('advanced', ['fetchTagData']),
    mapActions('node', ['fetchNodeData']),
    {
    // 解析资源状态消息
    parseResStatusMsg: parseResStatusMsg,

    // 解析资源状态颜色
    parseResStatusColor: parseResStatusColor,

    // 加载数据
    loadData() {
      const self = this
      // 并行加载Tag数据和节点数据
      Promise.all([
        this.fetchTagData(),
        this.fetchNodeData()
      ]).then(function () {
        // 数据加载成功
      }).catch(function (error) {
        self.$message.error(error || '获取数据失败')
      })
    },

    // 添加或编辑Tag
    handleAddOrEditTag(type) {
      if (type === 'add') {
        this.dialogTitle = '创建Tag'
        this.tagId = ''
      } else {
        this.dialogTitle = '编辑Tag'
        // 从选中的Tag ID中提取Tag名称（去掉可能的后缀）
        this.tagId = this.selectedTagId.split(':')[0]
      }
      this.dialogType = 'add_or_edit'
      this.dialogVisible = true
    },

    // 弹窗关闭
    handleDialogClose(type) {
      this.dialogVisible = false
      this.dialogType = ''
      this.dialogTitle = ''
      this.tagId = ''

      // 如果是成功操作，刷新数据
      if (type === 'success') {
        this.loadData()
      }
    },

    // 表格行选择变化
    handleCurrentChange(row) {
      if (row) {
        this.selectedTagId = row.id
        this.selectedTag = Object.assign({}, row)
        console.log('选中的Tag:', this.selectedTag)
      } else {
        this.selectedTagId = ''
        this.selectedTag = null
      }
    },

    // 刷新数据
    handleRefresh() {
      this.loadData()
    },

    // Tag操作（启动、停止、删除）
    handleTagOperation(row, type) {
      const self = this
      if (!row || !row.id) {
        this.$message.warning('请先选择一个Tag')
        return
      }

      tagActions(row.id, type)
        .then(function (res) {
          if (res.data.action) {
            // 延迟3秒后刷新列表
            setTimeout(function () {
              self.$message.success(res.data.info || '操作成功')
              self.loadData()
            }, 3000)
          } else {
            self.$message.error(res.data.error || '操作失败')
          }
        })
        .catch(function (err) {
          console.error('Tag操作失败:', err)
          self.$message.error('操作失败')
        })
    },

    // 确认删除
    confirmDelete() {
      this.deleteConfirmVisible = false
      this.handleTagOperation(this.selectedTag, 'delete')
    },

    // 点击节点
    handleClickNode(node) {
      this.selectedNode = Object.assign({}, node)
      this.nodePanelVisible = true
      console.log('选中的节点:', this.selectedNode)
    },

    // 关闭节点操作面板
    closeNodePanel() {
      this.nodePanelVisible = false
      this.selectedNode = {}
    },
  }),
}
</script>

<style lang="scss" scoped>
.tag-container {
  padding: 20px;
  position: relative;

  .tag-operations {
    padding: 12px;
    display: flex;
    justify-content: space-between;
    background: #f6f8fd;
    border-bottom: 2px solid #e4eaf9;
    margin-bottom: 20px;

    .operations-left {
      display: flex;
      gap: 12px;

      .operation-dropdown {
        margin-right: 12px;
      }
    }
  }

  .tag-table {
    // 隐藏全选按钮
    ::v-deep .el-table__header-wrapper .el-checkbox {
      display: none;
    }
  }
}

.expand-table {
  margin: 10px 40px;
}

.table-header-node {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: background-color 0.3s;

  &:hover {
    background-color: #f5f7fa;
  }

  .node-avatar {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    font-size: 12px;
    color: white;
    margin-right: 8px;

    &.node-running {
      background-color: #67c23a;
    }

    &.node-stopped {
      background-color: #f56c6c;
    }
  }

  .node-name {
    min-width: 40px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
  }
}

.node-panel {
  position: fixed;
  top: 0;
  right: 0;
  width: 350px;
  height: 100vh;
  background: white;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  display: flex;
  flex-direction: column;

  .node-panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .node-panel-content {
    flex: 1;
    padding: 16px;
    overflow-y: auto;

    p {
      margin: 10px 0;
      font-size: 14px;
      color: #606266;
    }
  }
}

.status-badge {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;

  &.badge-success {
    background-color: #67c23a;
  }

  &.badge-warning {
    background-color: #e6a23c;
  }

  &.badge-danger {
    background-color: #f56c6c;
  }

  &.badge-info {
    background-color: #909399;
  }

  &.badge-primary {
    background-color: #409eff;
  }
}

.radio {
  ::v-deep .el-radio__label {
    display: none;
  }
}
</style>
